<template>
  <el-table v-loading="loading" :data="tableData" :show-summary="showSummary" :summary-method="summaryMethod" stripe
    border
    :header-cell-style="{ background: '#F3F4F7', color: '#555',height: isFilterHeight?'70px':'auto',textAlign:'left' }"
    :row-key="getRowKey" @selection-change="selectionChangeFn" :height="height">
    <el-table-column v-for="column in columnList" :type="column.type" :key="column.field" :prop="column.field"
      :fixed="column.fixed" :sortable="column.sortable" :min-width="column.width" :show-overflow-tooltip="true">
      <template #header>
        <span>{{column.title}}</span>
        <div v-if="column.filterable" class="filter">
          <slot :name="column.field + '_' + 'filter'">
          </slot>
        </div>
      </template>
      <template #default="{row, $index}">
        <slot v-if="column.customText" :row="row" :index="$index" :name="column.field"></slot>
      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts" setup>
  import { cloneDeep } from 'lodash'

  const emit = defineEmits(['selectionChange'])

  const props = defineProps({
    loading: {
      type: Boolean,
      default: false
    },
    height: {
      type: String,
      default: 'calc(100vh - 370px)'
    },
    columns: {
      type: Array,
      default: [],
      required: true
    },
    dataSource: {
      type: Array,
      default: [],
      required: true
    },
    showSummary: {
      type: Boolean,
      default: false
    },
    getSummaries: Function
  })

  const columnList = ref([])

  const tableData = computed(() => {
    return props.dataSource
  })

  const isFilterHeight = computed(() => {
    return columnList.value.some(e => !!e.filterable)
  })

  watch(() => props.columns, (list) => {
    columnList.value = cloneDeep(list).filter(e => e.isShow)
  }, {
    immediate: true,
    deep: true
  })

  const getRowKey = (row) => {
    return row.id;
  }

  const selectionChangeFn = (selections) => {
    emit('selectionChange', selections)
  }

  const summaryMethod = (param) => {
    if (props.getSummaries) {
      return props.getSummaries(param)
    }
  }

</script>
<style lang="scss" scoped>
  .filter {
    width: calc(100% - 24px);
    position: absolute;
  }

  ::v-deep.el-table th.el-table__cell {
    vertical-align: top !important;
  }
</style>